/*
 * DemoMediaChannel.cpp
 *
 *  Created on: 2017年8月20日
 *      Author: terry
 */

#include "DemoMediaChannel.h"
#include "TFileUtil.h"
#include "Path.h"
#include "TThread.h"
#include "CLog.h"

namespace av
{


DemoMediaChannel::DemoMediaChannel():
	m_id(),
	m_threadId()
{
	m_source.setSink(this);
}

DemoMediaChannel::~DemoMediaChannel()
{
	close();
}

void DemoMediaChannel::setDevice(const std::string& id, const std::string& name)
{
	m_id = id;
	m_name = name;

	std::string filepath = comn::Path::getWorkDir();
	m_url = comn::Path::join(filepath, "num.pcma");

}

//void DemoMediaChannel::setFilePath(const std::string& filepath)
//{
//
//}

int DemoMediaChannel::open(const std::string& url, const std::string& params)
{
	if (isOpen())
	{
		close();
	}

	m_source.open(m_url.c_str());

	m_format.m_audioCodec = MEDIA_CODEC_G711A;
	m_format.m_channels = 1;
	m_format.m_sampleBits = 16;
	m_format.m_sampleRate = 8000;

	return 0;
}

void DemoMediaChannel::close()
{
	m_source.close();
	m_threadId = 0;
}

bool DemoMediaChannel::isOpen()
{
	return m_source.isOpen();
}


std::string DemoMediaChannel::getUrl()
{
	return m_url;
}


int DemoMediaChannel::startStream()
{
	setState(STATE_PLAYING);
	return 0;
}


int DemoMediaChannel::pauseStream()
{
	setState(STATE_PAUSED);
	return 0;
}


void DemoMediaChannel::stopStream()
{
	setState(STATE_STOPPED);
}


int DemoMediaChannel::forceKeyFrame()
{
	return 0;
}


void DemoMediaChannel::onMediaFormat(const MediaFormat& fmt)
{
	// pass
}


void DemoMediaChannel::onMediaPacket(MediaPacketPtr& pkt)
{
	if (!pkt)
	{
		return;
	}

	if (pkt->isVideo())
	{
		return;
	}

	DWORD currentId = GetCurrentThreadId();
	if (m_threadId == 0)
	{
		m_threadId = currentId;
		CLog::info("DemoMediaChannel::onMediaPacket thread: %d\n", currentId);
	}
	else if (m_threadId != currentId)
	{
		CLog::error("------------------- different thread. prev: %d, cur: %d\n", m_threadId, currentId);
	}

	std::string filename = m_id + ".audio";
	comn::FileUtil::write(pkt->data(), pkt->size(), filename.c_str(), true);

}


void DemoMediaChannel::onMediaEvent(int event)
{
	// pass
}

std::string DemoMediaChannel::getName()
{
	return m_name;
}

std::string DemoMediaChannel::getId()
{
	return m_id;
}

void DemoMediaChannel::onPcmData(uint8_t* data, size_t size, int64_t pts)
{
	MediaPacketPtr pkt(new MediaPacket());
	pkt->copy((unsigned char*)data, size);
	pkt->set_type(MEDIA_TYPE_AUDIO);

	int duration = size;

	pkt->set_dts(pts);
	pkt->set_pts(pts);

	fireMediaPacket(pkt);
}


}